/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package librairie;

import exception.CommunicationException;
import exception.ReadingObjectException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 *
 * @author Khémon Beh & Florian Minin
 */
public class Transport implements InterfaceTransport {

    private String host;
    private int port;
    private ObjectOutputStream out;
    private ObjectInputStream in;
    private Socket s;

    public Transport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public Transport(Socket _s) {
        s = _s;
    }

    public void connecter() throws CommunicationException{
        try {
            if (s == null) {
                s = new Socket(host, port);
                out = new ObjectOutputStream(s.getOutputStream());
                in = new ObjectInputStream(s.getInputStream());
            } else { 
                in = new ObjectInputStream(s.getInputStream());
                out = new ObjectOutputStream(s.getOutputStream());
            }
        } catch (IOException ioe) {
            throw new CommunicationException();
        }
    }

    public void envoyer(Object m) throws CommunicationException {
        try {
            out.writeObject(m);
        } catch (IOException ioe) {
            throw new CommunicationException();
        }
    }

    public Object recevoir() throws CommunicationException, ReadingObjectException {
        try {
            return in.readObject();
        } catch (IOException ioex) {
            throw new CommunicationException();
        } catch (ClassNotFoundException cnfe) {
            throw new ReadingObjectException();
        }
    }

    public void fermer() throws CommunicationException {
        try {
            out.close();
            in.close();
            s.close();
            s = null;
        } catch (IOException ioex) {
            throw new CommunicationException();
        }
    }
}
